package com.pioneer.fationservice.serviceinfos;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.pioneer.fationservice.R;
import com.pioneer.fationservice.adapters.RecommentAdapter;
import com.pioneer.fationservice.commons.SystemData;
import com.pioneer.fationservice.commons.SystemHttpURL;
import com.pioneer.fationservice.models.ResponseObject;
import com.pioneer.fationservice.parsers.BaseParser;
import com.pioneer.fationservice.selfctls.InnerGridView;

public class RecommentActivity extends FinalActivity {
	
	@ViewInject(id=R.id.layout_actionbar_txtTitle) private TextView txtTitle;//标题栏
	@ViewInject(id=R.id.activity_recomment_imgBack,click="onBackClick") private ImageView imgBack;//返回操作
	@ViewInject(id=R.id.activity_recomment_etTitle) private EditText etTitle;//标题栏
	@ViewInject(id=R.id.activity_recomment_etContent) private EditText etContent;//要提交的内容
	@ViewInject(id=R.id.activity_recomment_igPics) private InnerGridView igPics;//要提交的图片
	@ViewInject(id=R.id.activity_recomment_txtSubmit,click="txtSubmitClick") private TextView txtSubmit;//提交反馈
	
	private List<String> piclst = new ArrayList<String>();//图片集合列表
	private RecommentAdapter reAdapter;//图片数据适配器
	private static final int MAX_UPLOAD_PIC_COUNT = 4;//最大上传图片数
	private int selectedPicIndex = 0;//当前选中 图片
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_recomment);
		txtTitle.setText("投诉建议");
		piclst.add("--add--");
		reAdapter = new RecommentAdapter(this, piclst);
		igPics.setHorizontalSpacing(5);
		igPics.setVerticalSpacing(5);
		igPics.setNumColumns(4);
		igPics.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				final String item = piclst.get(position);
				selectedPicIndex = position;
				if(item.equals("--add--")) viewPictureLibray();//浏览图库
				else{
					
				}
			}
		});
		igPics.setAdapter(reAdapter);
	}
	
	/**
	 * 提交反馈按钮
	 * @param view
	 */
	public void txtSubmitClick(View view){
		String strTitle = etTitle.getText().toString();
		if(TextUtils.isEmpty(strTitle)){
			Toast.makeText(this, "标题不能为空!", Toast.LENGTH_SHORT).show();
			return;
		}
		String strContent = etContent.getText().toString();
		if(TextUtils.isEmpty(strContent)){
			Toast.makeText(this, "内容不能为空!", Toast.LENGTH_SHORT).show();
			return;
		}
		submitRecomment();//提交用户建议
	}
	
	/**
	 * 浏览图库
	 */
	public void viewPictureLibray(){
		Intent intent = new Intent(Intent.ACTION_PICK, 
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(intent,0x001);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == 0x001 && resultCode == Activity.RESULT_OK && data!=null){
			Uri selectedImage = data.getData();
	        String[] filePathColumn = { MediaStore.Images.Media.DATA };
	        Cursor cursor = getContentResolver().query(selectedImage,
	                filePathColumn, null, null, null);
	        cursor.moveToFirst();
	        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	        String picturePath = cursor.getString(columnIndex);
	        cursor.close();
			if(selectedPicIndex < MAX_UPLOAD_PIC_COUNT-1){
				piclst.add(selectedPicIndex == 0?0:selectedPicIndex-1,picturePath);
			}else{
				piclst.remove(MAX_UPLOAD_PIC_COUNT-1);
				piclst.add(picturePath);
			}
			reAdapter.notifyDataSetChanged();
		}
	}
	
	/**
	 * 返回操作
	 * @param view
	 */
	public void onBackClick(View view){
		this.finish();
		overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
	}
	
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK){
    		imgBack.performClick();//模拟点击返回按钮
    		return true;
    	}
    	return super.onKeyDown(keyCode, event);
    }
    
	/**
	 * 上传用户头像
	 */
	public void submitRecomment(){
		try{
			final ProgressDialog dialog = ProgressDialog.show(this, "", "正在提交...");
			FinalHttp finalHttp = new FinalHttp();
			AjaxParams params = new AjaxParams();
			params.put("uid", String.valueOf(SystemData.uid));
			params.put("title",etTitle.getText().toString());
			params.put("content", etContent.getText().toString());
			for(String item : piclst){
				if(!item.equals("--add--")) 
					params.put("file_"+System.currentTimeMillis(), new File(item));
			}
			finalHttp.post(SystemHttpURL.URL_COMPLAINT, params,new AjaxCallBack<String>() {
				@Override
				public void onFailure(Throwable t, int errorNo, String strMsg) {
					super.onFailure(t, errorNo, strMsg);
					if(dialog!=null) dialog.dismiss();
					Toast.makeText(RecommentActivity.this, "网络错误，提交失败!",Toast.LENGTH_SHORT).show();
				}
				@Override
				public void onSuccess(String str) {
					super.onSuccess(str);
					if(dialog!=null) dialog.dismiss();
					System.out.println("投诉建议信息--结果返回："+str);
					ResponseObject model = new BaseParser(ResponseObject.class,str){
						@Override
						public void parseJSONModels(Object jsonModels,boolean isJSONObject) {
						}
					}.getResponseObject();
					switch(model.status){
					case 1:
						//重置页面数据
						etTitle.setText("");
						etContent.setText("");
						piclst.clear();
						piclst.add("--add--");
						reAdapter.notifyDataSetChanged();
						Toast.makeText(RecommentActivity.this, "提交反馈成功！",Toast.LENGTH_SHORT).show();
						break;
					default:
						Toast.makeText(RecommentActivity.this,model.msg,Toast.LENGTH_SHORT).show();
						break;
					}
				}
			});
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
    
    
}
